<template>
  <view class="after-sales-container">
    <!-- 售后列表项 -->
    <view 
      class="after-sales-item"
      v-for="service in afterSalesList" 
      :key="service.id"
    >
      <view class="service-header">
        <text 
          class="service-no" 
          @longpress="copyToClipboard(service.id)"
        >服务单号：{{ service.id }}</text>
        <text class="service-status" :class="service.serviceStatus">
          {{ getServiceStatusText(service.serviceStatus) }}
        </text>
      </view>
      
      <view class="related-order">
        <text 
          class="order-no" 
          @longpress="copyToClipboard(service.orderId)"
        >关联订单：{{ service.orderId }}</text>
        <text class="service-type">{{ getServiceTypeText(service.serviceType) }}</text>
      </view>

      <view class="service-reason">
        <text class="label">申请原因：</text>
        <text class="content">{{ service.serviceReason }}</text>
      </view>

      <view class="service-images" v-if="service.serviceImages">
        <image 
          v-for="(img, index) in service.serviceImages.split(',')" 
          :key="index"
          :src="img" 
          mode="aspectFill"
          class="evidence-image"
          @tap="handleImagePreview(img)"
        />
      </view>

      <view class="service-actions">
        <button 
          class="action-btn" 
          @tap="handleViewDetail(service.id)"
        >查看详情</button>
        <button 
          v-if="service.serviceStatus === 'pending'"
          class="action-btn cancel-btn"
          @tap="handleCancel(service.id)"
        >取消申请</button>
      </view>
    </view>

    <!-- 空状态 -->
    <view class="empty-state" v-if="afterSalesList.length === 0">
      <image src="/static/empty-order.png" mode="aspectFit" class="empty-icon"/>
      <text class="empty-title">暂无售后记录</text>
      <text class="empty-desc">您还没有任何售后申请记录</text>
      <button class="go-shopping-btn" @tap="goToHome">去逛逛</button>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import {
  cancelAfterSalesServiceUsingPost,
  listMyAfterSalesServiceVoByPageUsingPost
} from '@/backend/afterSalesServiceController';
import type { API } from '@/backend/typings';
import type { ComponentInternalInstance } from 'vue';
import type Uni from '@dcloudio/uni-app';

declare const uni: Uni;

const afterSalesList = ref<API.AfterSalesServiceVO[]>([]);
const pagination = ref({
  current: 1,
  pageSize: 10,
  total: 0
});

// 获取售后列表
const loadAfterSales = async () => {
  try {
    const res = await listMyAfterSalesServiceVoByPageUsingPost({
      current: pagination.value.current,
      pageSize: pagination.value.pageSize,
      sortField: 'createTime',
      sortOrder: 'desc' // 按创建时间倒序，新订单在前
    });
    
    if (res.code === 0 && res.data) {
      afterSalesList.value = res.data.records || [];
      pagination.value.total = res.data.total || 0;
    } else {
      uni.showToast({
        title: res.message || '获取售后列表失败',
        icon: 'none'
      });
    }
  } catch (error) {
    console.error('获取售后列表失败:', error);
    uni.showToast({
      title: '获取售后列表失败',
      icon: 'none'
    });
  }
};

// 状态映射
const getServiceStatusText = (status?: string) => {
  const statusMap: Record<string, string> = {
    pending: '待处理',
    processing: '处理中',
    completed: '已完成',
    cancelled: '已取消',
    rejected: '已拒绝'
  };
  return status && status in statusMap ? statusMap[status] : '未知状态';
};

const getServiceTypeText = (type?: string) => {
  const typeMap: Record<string, string> = {
    refund: '仅退款',
    return: '退货',
    exchange: '换货'
  };
  return type && type in typeMap ? typeMap[type] : '未知类型';
};

// 图片预览
const handleImagePreview = (img: string) => {
  uni.previewImage({
    urls: [img]
  });
};

// 查看详情
const handleViewDetail = (id?: number) => {
  if (!id) return;
  uni.navigateTo({
    url: `/pages/afterSales/detail?id=${id}`
  });
};

// 取消申请
const handleCancel = (id?: number) => {
  if (!id) return;
  uni.showModal({
    title: '取消申请',
    content: '确定要取消该售后申请吗？',
    success: async (res) => {
      if (res.confirm) {
        const res = await cancelAfterSalesServiceUsingPost({
          id: id
        });
        uni.showToast({
          title: '取消成功',
          icon: 'success'
        });
        await loadAfterSales(); // 刷新列表
      }
    }
  });
};

// 跳转到首页
const goToHome = () => {
  uni.switchTab({
    url: '/pages/home/home'
  });
};

// 在script部分添加复制方法
const copyToClipboard = (text: string | number) => {
  uni.setClipboardData({
    data: String(text),
    success: () => {
      uni.showToast({
        title: '已复制到剪贴板',
        icon: 'none'
      });
    },
    fail: (err) => {
      console.error('复制失败:', err);
      uni.showToast({
        title: '复制失败',
        icon: 'none'
      });
    }
  });
};

// 暴露方法给父组件
defineExpose({
  loadAfterSales
});

onMounted(() => {
  loadAfterSales();
});
</script>

<style scoped>
.after-sales-container {
  padding: 20rpx;
}

.after-sales-item {
  background: #fff;
  border-radius: 16rpx;
  padding: 24rpx;
  margin-bottom: 20rpx;
}

.service-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
}

.service-no,
.order-no {
  user-select: text;
  -webkit-user-select: text;
}

.service-no {
  font-size: 24rpx;
  color: #999;
}

.service-status {
  font-size: 26rpx;
  font-weight: 500;
}

.service-status.pending {
  color: #ff9800;
}

.service-status.processing {
  color: #2196f3;
}

.service-status.completed {
  color: #4caf50;
}

.service-status.rejected {
  color: #f44336;
}

.related-order {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16rpx;
}

.order-no {
  font-size: 24rpx;
  color: #666;
}

.service-type {
  font-size: 24rpx;
  color: #ff5722;
  background: #fff2ed;
  padding: 4rpx 12rpx;
  border-radius: 4rpx;
}

.service-reason {
  margin-bottom: 16rpx;
}

.label {
  font-size: 26rpx;
  color: #666;
}

.content {
  font-size: 26rpx;
  color: #333;
}

.service-images {
  display: flex;
  gap: 16rpx;
  margin-bottom: 20rpx;
}

.evidence-image {
  width: 160rpx;
  height: 160rpx;
  border-radius: 8rpx;
}

.service-actions {
  display: flex;
  justify-content: flex-end;
  gap: 20rpx;
}

.action-btn {
  min-width: 160rpx;
  height: 64rpx;
  font-size: 26rpx;
  border-radius: 32rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0 32rpx;
  background: #fff;
  color: #666;
  border: 2rpx solid #ddd;
}

.cancel-btn {
  color: #f44336;
  border-color: #f44336;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 120rpx 40rpx;
  background: #fff;
  border-radius: 16rpx;
  margin: 20rpx;
}

.empty-icon {
  width: 240rpx;
  height: 240rpx;
  margin-bottom: 40rpx;
}

.empty-title {
  font-size: 32rpx;
  color: #333;
  font-weight: 500;
  margin-bottom: 16rpx;
}

.empty-desc {
  font-size: 26rpx;
  color: #999;
  margin-bottom: 40rpx;
}

.go-shopping-btn {
  width: 240rpx;
  height: 80rpx;
  background: linear-gradient(135deg, #ff9800, #ff5722);
  color: #fff;
  font-size: 28rpx;
  border-radius: 40rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 8rpx 16rpx rgba(255, 87, 34, 0.2);
}
</style> 